import React, { useState } from 'react';
import { Form, Button, DatePicker } from 'antd';
import moment from 'moment';

const { RangePicker } = DatePicker;

const Search = ({ query, onSearch }) => {
    const [queryDate, setQueryDate] = useState([
        query.versionStartDate ? moment(query.versionStartDate) : null,
        query.versionEndDate ? moment(query.versionEndDate) : null
    ]);

    // 查询
    const handleSearch = e => {
        e.preventDefault();
        let versionEndDate = null;
        let versionStartDate = null;
        let payload = {};
        if (queryDate.length > 0) {
            versionStartDate = queryDate[0].format('YYYY-MM-DD');
            versionEndDate = queryDate[1].format('YYYY-MM-DD');
        }
        payload = {
            versionStartDate,
            versionEndDate
        };
        if (onSearch) {
            onSearch(payload);
        }
    };

    // 选择日期
    const dateChange = e => {
        let arr = [];
        if (e.length > 0) {
            arr = [moment(e[0]), moment(e[1])];
        }
        setQueryDate(arr);
    };

    return (
        <Form layout="inline" onSubmit={handleSearch}>
            <Form.Item label="版本开始时间">
                <RangePicker allowClear value={queryDate} onChange={dateChange} format="YYYY-MM-DD" />
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">
                    查询
                </Button>
            </Form.Item>
        </Form>
    );
};

export default Search;
